<template>
  <base-layout simple>
    <article class="base-layout__inner column">
      <!-- 控制按钮 -->
      <t-space>
        <t-button @click="handleAdd">新增组织</t-button>
        <t-button theme="default" @click="onExpandAllToggle">
          {{ expandAll ? '收起全部' : '展开全部' }}
        </t-button>
      </t-space>

      <!-- 树形表格 -->
      <t-enhanced-table
        ref="table"
        row-key="id"
        :data="data"
        :columns="columns"
        :tree="{
          childrenKey: 'children',
          treeNodeColumnIndex: 0,
          expandTreeNodeOnClick: false,
          indent: 44,
        }"
        :expanded-tree-nodes.sync="expandedTreeNodes"
        :loading="loading"
        bordered
        size="small"
      />
    </article>

    <!-- 租户编辑器 -->
    <tenant-editor
      v-model="editorVisible"
      :edit-data="currentEditData"
      @save="handleSave"
    />
  </base-layout>
</template>

<script>
import BaseLayout from '@/components/base-layout/index.vue';
import { Button as TButton, Tag as TTag, EnhancedTable } from 'tdesign-vue';
import { getAllDepts, delTenant } from '@/api/dept';
import TenantEditor from './tenant-editor.vue';

export default {
  name: 'SystemTenant',
  components: {
    BaseLayout,
    TEnhancedTable: EnhancedTable,
    TenantEditor,
  },
  data() {
    return {
      loading: false,
      expandAll: true,
      expandedTreeNodes: [],
      editorVisible: false,
      currentEditData: null,
      isEdit: false,

      // 表格列配置
      columns: [
        {
          colKey: 'name',
          title: '租户名称',
          width: 250,
          ellipsis: true,
        },
        {
          colKey: 'code',
          title: '租户编码',
          width: 220,
          cell: (h, { row }) => {
            return row.code
              ? h(
                  TTag,
                  {
                    props: {
                      variant: 'light',
                      theme: 'primary',
                    },
                  },
                  row.code
                )
              : null;
          },
        },
        {
          colKey: 'status',
          title: '状态',
          width: 100,
          cell: (h, { row }) => {
            return row.status !== undefined
              ? h(
                  TTag,
                  {
                    props: {
                      theme: row.status === 1 ? 'success' : 'danger',
                      size: 'small',
                      variant: 'light',
                    },
                  },
                  row.status === 1 ? '启用' : '禁用'
                )
              : null;
          },
        },
        {
          colKey: 'servicePhone',
          title: '服务电话',
          width: 150,
        },
        {
          colKey: 'address',
          title: '地址',
          width: 200,
          ellipsis: true,
        },
        {
          colKey: 'workTime',
          title: '工作时间',
          width: 200,
        },
        {
          colKey: 'createdAt',
          title: '创建时间',
          width: 180,
        },
        {
          colKey: 'operate',
          title: '操作',
          width: 120,
          fixed: 'right',
          cell: (h, { row }) => (
            <div class='table-operations'>
              <t-button
                variant='text'
                theme='primary'
                size='small'
                onClick={() => this.handleEdit(row)}
              >
                编辑
              </t-button>
              <t-popconfirm content='确认删除吗？' onConfirm={() => this.handleDelete(row)}>
                <t-button variant='text' theme='danger' size='small'>
                  删除
                </t-button>
              </t-popconfirm>
            </div>
          ),
        },
      ],

      // 树形数据
      data: [],
    };
  },

  mounted() {
    this.getList();
  },

  methods: {
    // 获取数据
    async getList() {
      this.loading = true;
      try {
        const res = await getAllDepts({ page: 1, pageSize: 20 });
        console.log('获取到的数据:', res);
        const items = res?.data?.data ?? [];

        // 转换为树形结构（如果后端数据不是树形结构）
        this.data = this.ensureTreeStructure(items);
        console.log('处理后的树形数据:', this.data);

        // 数据加载完成后，等待DOM更新，然后展开全部
        this.$nextTick(() => {
          if (this.$refs.table && this.data.length > 0) {
            // 清除之前的展开状态
            this.expandedTreeNodes = [];
            // 等待一个更长的时间确保DOM完全更新
            setTimeout(() => {
              if (this.$refs.table) {
                this.$refs.table.expandAll();
              }
            }, 100);
          }
        });
      } catch (error) {
        this.data = [];
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    // 确保数据有树形结构
    ensureTreeStructure(items) {
      if (!items || items.length === 0) {
        return [];
      }

      // 如果数据已经有树形结构，确保每个节点都有children属性
      if (items.some((item) => item.children && Array.isArray(item.children))) {
        return items.map(item => ({
          ...item,
          children: item.children && item.children.length > 0 ?
            this.ensureTreeStructure(item.children) : []
        }));
      }

      // 如果数据是平铺的，根据 parentId 构建树形结构
      const tree = [];
      const map = {};

      // 创建映射，确保每个节点都有children数组
      items.forEach((item) => {
        map[item.id] = { ...item, children: [] };
      });

      // 构建树形结构
      items.forEach((item) => {
        if (item.parentId && map[item.parentId]) {
          map[item.parentId].children.push(map[item.id]);
        } else {
          tree.push(map[item.id]);
        }
      });

      return tree;
    },

    // 展开/收起全部
    onExpandAllToggle() {
      this.expandAll = !this.expandAll;
      this.expandAll ? this.$refs.table.expandAll() : this.$refs.table.foldAll();
    },

    // 新增
    handleAdd() {
      this.isEdit = false;
      this.currentEditData = null;
      this.editorVisible = true;
    },

    // 编辑
    handleEdit(row) {
      this.isEdit = true;
      this.currentEditData = { ...row };
      this.editorVisible = true;
    },    // 保存处理
    async handleSave() {
      // 无论是编辑还是新增，都刷新整个列表以获取最新数据
      console.log('操作成功，准备刷新列表');
      await this.getList();

      this.editorVisible = false;
      this.currentEditData = null;
    },

    // 删除
    async handleDelete(row) {
      try {
        if (typeof row.id === 'number') {
          const res = await delTenant(row.id);
          const { code, message } = res?.data ?? {};

          if (code === 200) {
            this.$refs.table.remove(row.id);
            this.$message.success('删除成功');
          } else {
            throw new Error(message ?? '删除失败');
          }
        } else {
          this.$refs.table.remove(row.id);
          this.$message.success('删除成功');
        }
      } catch (error) {
        this.$message.error(error?.message ?? '删除失败');
      }
    },
  },
};
</script>

<style lang="less" scoped>
:deep(.table-operations) {
  .t-button {
    margin-right: 8px;
  }
}
</style>
